package osgi.common.services.job.groovy;

import groovy.lang.GroovyClassLoader;

import java.io.File;
import java.io.IOException;

import org.codehaus.groovy.control.CompilationFailedException;
import org.osgi.service.component.ComponentContext;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import osgi.common.services.job.client.AbstractJobService;

public class GroovyJobService extends AbstractJobService implements	ICommonGroovyJob {


	private GroovyClassLoader loader;
	private String groovyScriptPath;

	public GroovyJobService() {
		super();

	}

	@Override
	public void execute(JobExecutionContext execContext) throws JobExecutionException {
		logger.info("execute(JobExecutionContext) - start");

		if (this.groovyScriptPath != null) {
			try {
				File groovyFile = new File(this.groovyScriptPath);
				if (groovyFile.exists()) {
					loader.clearCache();
					Class groovyClass = loader.parseClass(groovyFile);
					
					Object aScript = groovyClass.newInstance();
					Job myJob = (Job) aScript;
					
					execContext.getMergedJobDataMap().put("logger", this.logger);
					execContext.getMergedJobDataMap().put("quartzService", this.quartz);
					execContext.getMergedJobDataMap().put("jobKey", this.jobKey);
					execContext.getMergedJobDataMap().put("configProperties", this.configProperties);
					execContext.getMergedJobDataMap().put("context", this.context);
								
					myJob.execute(execContext);
					
				} else {
					logger.warn("Groovy Script not Found : " + this.groovyScriptPath);
				}
			} catch (CompilationFailedException e) {
				logger.error("execute(JobExecutionContext)", e);

				e.printStackTrace();
			} catch (IOException e) {
				logger.error("execute(JobExecutionContext)", e);

				e.printStackTrace();
			} catch (InstantiationException e) {
				logger.error("execute(JobExecutionContext)", e);

				e.printStackTrace();
			} catch (IllegalAccessException e) {
				logger.error("execute(JobExecutionContext)", e);

				e.printStackTrace();
			}
		} else {
			logger.warn("Groovy Script CANNOT BE NULL !");
		}

		logger.info("execute(JobExecutionContext) - end");
	}

	@Override
	public void activate(ComponentContext context) {

		super.activate(context);

		ClassLoader parentCL = this.getClass().getClassLoader();
		loader = new GroovyClassLoader(parentCL);

		// Class groovyClass = loader.parseClass(new
		// File("c:/HelloWorld.groovy"));

		if (this.groovyScriptPath == null) {
			throw new RuntimeException("Groovy Script CANNOT BE NULL !");
		}

	}

	@Override
	public void setGroovyScript(String groovyScriptPath) {
		this.groovyScriptPath = groovyScriptPath;

	}

	@Override
	public String getGroovyScript() {
		return this.groovyScriptPath;
	}

}
